package com.gitee.wsl.net.server.role.admin

import com.gitee.wsl.ext.base.currentTimeMillis
import com.gitee.wsl.net.exceptions.Exceptions
import com.gitee.wsl.net.server.AppConstants
import io.ktor.server.auth.AuthenticationConfig
import io.ktor.server.auth.session

interface SessionService {
    /**
     * Generate token
     */
    fun generateToken(
        userId: Int,
        timestamp: Long = currentTimeMillis
    ): String

    /**
     * Get user by id
     */
    suspend fun findUserByID(userId: Int)

    /**
     * Verify refresh token with get user ID
     */
    fun verify(value: String): Int?

    /**
     * (24 hours) * 30 days
     */
    private fun Long.expiresAt() = (this + 3_600_000 * 24) * 30
}

fun AuthenticationConfig.authentication(sessionService: SessionService) {

    //val sessionService: SessionService by inject(SessionService::class.java)

    session<SessionUser>(AppConstants.SESSION_KEY) {
        validate { session ->
            sessionService.verify(session.token)?.let { userId ->
                return@validate sessionService.findUserByID(userId)?.let { session }
                    ?: throw Exceptions.Unauthorized()
            }
        }
        challenge {
            // Guest
        }
    }
}